
import html2canvas from "html2canvas";
export const useHtml2Image = () => {
    const dataURLtoBlob = (dataurl: string) => {
        let arr = dataurl.split(',') as string[];
        let header = arr[0] as string
        let mime = (header.match(/:(.*?);/) as string[])[1]
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
    }

    const downloadFile = (url: string, name = 'What\'s the fuvk') => {

        console.log(555)

        var a = document.createElement('a')

        a.setAttribute('href', url)

        a.setAttribute('download', name)

        a.setAttribute('target', '_blank')

        const clickEvent = document.createEvent('MouseEvents')

        clickEvent.initEvent('click', true, true)

        a.dispatchEvent(clickEvent)

    }

    const downloadFileByBase64 = (base64: string, name: string) => {

        console.log(333)

        var myBlob = dataURLtoBlob(base64)

        var myUrl = URL.createObjectURL(myBlob)

        downloadFile(myUrl, name)

        // console.log(base64)

    }

    const getIdCarema = (id: string) => {

        console.log(111)

        var element = document.getElementById(id)

        html2canvas(element as HTMLElement, {

            backgroundColor: 'transparent',

            logging: false,
            
        }).then(canvas => {

            const context = canvas.getContext('2d') as CanvasRenderingContext2D
            // // 关闭抗锯齿形
            // debugger 无以下属性
            // if(context.mozImageSmoothingEnabled)
            // context.mozImageSmoothingEnabled = false

            // context.webkitImageSmoothingEnabled = false

            // context.msImageSmoothingEnabled = false

            // context.imageSmoothingEnabled = false

            // canvas转化为图片

            canvas2Image(canvas, canvas.width, canvas.height, id, '图片' + Date.now())


        })

    }

    const canvas2Image = (canvas: HTMLCanvasElement, width: number, height: number, id: string, val: string) => {

        console.log(222, canvas, width, height, id, val) // <canvas width="2312" height="1360" style="width: 1156px; height: 680px;"></canvas> 2312 1360 "container" "图片"

        const retCanvas = document.createElement('canvas')

        const retCtx = retCanvas.getContext('2d')

        console.log('retCanvas', retCanvas)

        retCanvas.width = width

        retCanvas.height = height

        retCtx?.drawImage(canvas, 0, 0, width, height, 0, 0, width, height)

        const img = document.createElement('img')

        img.src = retCanvas.toDataURL('image/png') // 可以根据需要更改格式

        // window.sessionStorage.setItem(id, retCanvas.toDataURL('image/png')) // ？

        downloadFileByBase64(retCanvas.toDataURL('image/png'), val)

    }
    return {
        getIdCarema
    }
}